package OptimalAlgorithm.BinarySearch;
//给你一个按照非递减顺序排列的整数数组 nums，和一个目标值 target。请你找出给定目标值在数组中的开始位置和结束位置。
//如果数组中不存在目标值 target，返回 [-1, -1]
//eg:
//输入：nums = [5,7,7,8,8,10], target = 8
//输出：[3,4]

public class SearchRange {
    public int[] searchRange(int[] nums, int target) {
        int[] ret = new int[]{-1,-1};
        if(nums == null || nums.length == 0){
            return ret;
        }
        int left = 0;
        int right = nums.length - 1;
        int mid = 0;
        //求左端点
        while(left < right){
            mid = left + (right - left) / 2;
            if(nums[mid] < target){
                left = mid + 1;
            }else {
                right = mid;
            }
        }
        if(nums[left] != target){
            return ret;
        }else {
            ret[0] = right;
        }
        left = 0;
        right = nums.length - 1;
        //求右端点
        while (left < right){
            mid = left + (right - left + 1) / 2;
            if(nums[mid] > target){
                right = mid - 1;
            }else {
                left = mid;
            }
        }
        if(nums[left] != target){
            return ret;
        }else {
            ret[1] = right;
        }
        return ret;
    }
}
